package by.yativem.commons.thread;

import org.apache.log4j.Logger;

import by.yativem.commons.task.AbstractTask;

public class ThreadWorker extends Thread {
	private static final Logger log = Logger.getLogger(ThreadWorker.class);
	private final Object lock = new Object();
	private volatile boolean isRunning;
	private Runnable target;
	private int workerId;

	public synchronized void processThread(Runnable r) {
		if (isRunning) {
			throw new IllegalStateException(
					"Worker is currently running and could not processs new works");
		}
		target = r;
		synchronized (lock) {
			lock.notifyAll();
		}
		
	}

	public ThreadWorker( int workerId) {		
		super();
		this.workerId = workerId;
	}

	public ThreadWorker( int workerId ,Runnable r) {
		this(workerId);
		target = r;

	}

	@Override
	public void run() {
		isRunning = true;
		while (true) {
			try {
				if (target != null) {
					if(target instanceof AbstractTask){
						
						this.setName(getWorkerName());
					}
					log.info(getWorkerName() + "is started");
					target.run();
					log.info(getWorkerName() + "is finished");
				}
			} catch (Exception e) {
				log.error("", e);
			} finally {
				isRunning = false;
				try {
					synchronized (lock) {
						
					
					lock.wait();
					}
					
				} catch (Exception e2) {
					log.error("", e2);// TODO: handle exception
				}

			}
		}

	}

	public boolean isRunning() {
		return isRunning;
	}
	
	
	private String getWorkerName(){
		if(target != null && target instanceof AbstractTask){
			return "Thread Worker : "+  workerId + " " + ((AbstractTask) target).getTaskName(); 
		}else{
			return "Thread Worker : "+  workerId + " ";
		}
	}

}
